import 'user_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class UserModelSingleton {
  static final UserModelSingleton _singleton = UserModelSingleton._internal();
  UserModel? _userModel;

  factory UserModelSingleton() {
    return _singleton;
  }

  UserModelSingleton._internal();

  UserModel? get userModel => _userModel;

  set userModel(UserModel? userModel) {
    _userModel = userModel;
    if (userModel != null) {
      saveUserModel(userModel);
    }
  }

  Future<void> saveUserModel(UserModel userModel) async {
    final prefs = await SharedPreferences.getInstance();
    final userModelJson = json.encode(userModel.toJson());
    await prefs.setString('userModel1', userModelJson);
  }

  Future<void> loadUserModel() async {
    final prefs = await SharedPreferences.getInstance();
    final userModelJson = prefs.getString('userModel1');
    if (userModelJson != null) {
      _userModel = UserModel.fromJson(json.decode(userModelJson));
    }
  }

  Future<void> clearUserModel() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('userModel');
  }

  bool isLoggedIn() {
    return _userModel != null;
  }
}